package practica3as;

import java.util.ArrayList;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;
import entities.*;

public class AnimationController extends Thread {

    private Drawable scene;
    private ArrayList<Ball> ballList;
    private boolean stop;
    private Semaphore semaphore;

    public AnimationController(Drawable scene) {
        ballList = new ArrayList<>();
        this.scene = scene;
        stop = false;
        semaphore = new Semaphore(1);
    }

    @Override
    public void run() {
        while (!stop) {
            try {
                semaphore.acquire();
                for (Ball b : ballList) {
                    synchronized (scene) {
                        Drawable d = scene.colision(b);
                    }
                    b.move();
                }
                semaphore.release();
                try {
                    Thread.sleep(5);
                } catch (InterruptedException ex) {
                    Logger.getLogger(AnimationController.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (Exception e) {
                Logger.getLogger(AnimationController.class.getName()).log(Level.SEVERE, null, e);
            }
        }
    }

    public void setStop(boolean stop) {
        this.stop = stop;
    }

    public void addBall(Ball b) {
        try {
            semaphore.acquire();
            ballList.add(b);
            scene.add(b);
            semaphore.release();
        } catch (InterruptedException ex) {
            Logger.getLogger(AnimationController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void setBallList(ArrayList<Ball> ballList) {
        try {
            semaphore.acquire();
            this.ballList = ballList;
            semaphore.release();
        } catch (InterruptedException ex) {
            Logger.getLogger(AnimationController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    void setScene(Composite scene) {
        synchronized (scene) {
            ballList = new ArrayList<>();
            for (int i = 0; i < scene.getSize(); i++){
                if (scene.getChild(i) instanceof Ball){
                    ballList.add((Ball) scene.getChild(i));
                }
            }
            this.scene = scene;
        }
    }

    public Drawable getScene() {
        return scene;
    }
}
